<template>
  <div style="display: flex" ref="imageWrapper">
    <div style="flex: 1; margin-right: 15px; max-width: 250px">
      <!-- :id="id"
       :isload="isload"
       @getTree="hadleGetTreeList" -->
      <LeftTree title="科目" ref="leftTree" @selected="getTreeData"></LeftTree>
    </div>
    <a-card v-if="tableShow" style="flex: 5; overflow: auto" :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline"
          @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-model-item label="账套/核算单元" prop="accName">
                <a-input @click.native="openOrganModel" v-model="queryParam.accName" readOnly
                  placeholder="请选择账套/核算单元" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="6">
              <a-form-model-item label="截止日期" prop="cutOffTime">
                <a-date-picker placeholder="请选择截止日期" value-format="YYYY-MM-DD" v-model="queryParam.cutOffTime" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="6">
              <a-form-model-item label="年度天数单位" prop="dayNum">
                <a-input-number style="width: 100%" placeholder="请输入1~366之间的数字" v-model="queryParam.dayNum" />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">清除条件</a-button>
              <a-button type="danger" :loading="ydLoading" @click="
                () => {
                  if (this.dataSource1.length) {
                    const { accYear = '', cutOffTime = '', dayNum = 365 } = this.queryParam
                    let ydnr = `【年度单位天数：${dayNum}】`
                    let time = `【${cutOffTime}前】【帐龄分析】`
                    this.addYd(queryParam, ydnr, time)
                  } else {
                    this.$message.error('空数据不能新建疑点')
                  }
                }
              " icon="arrow-right" style="margin-left: 8px">转疑点</a-button>
              <a-button v-if="isBackButton" type="primary" style="margin-left: 8px" @click="backUppage">
                返回
              </a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <h4 style="margin-bottom: 15px; color: #364174">账龄</h4>
      <div style="
          float: right;
          margin-right: 30px;
          margin-top: -40px;
          border: 1px solid red;
          border-radius: 3px;
          padding: 3px 5px;
          background: rgba(245, 77, 79, 0.2);
          color: red;
          font-size: 16px;
        ">
        单位：元
      </div>
      <!-- :pagination="ipagination" -->
      <a-table ref="table" size="middle" bordered rowKey="id" class="pointer_table" :scroll="{ x: 800, y: 300 }"
        :columns="columns1" :pagination="false" :dataSource="dataSource1" :loading="loading" :customRow="Rowclick">
      </a-table>

      <h4 style="margin: 15px 0; color: #364174">明细</h4>
      <!-- :pagination="ipagination" -->
      <a-table ref="table" size="middle" bordered rowKey="id" v-if="tableShow2" :scroll="{ y: 300 }" :columns="columns2"
        :dataSource="dataSource2" :pagination="ipagination" :loading="loading" @change="handleTableChange">
        <template v-slot:unitName="text">
          <j-ellipsis :value="text" :length="7" />
        </template>
        <template v-slot:summary="text">
          <j-ellipsis :value="text" :length="6" />
        </template>
        <template v-slot:accName="text">
          <j-ellipsis :value="text" :length="8" />
        </template>
      </a-table>
    </a-card>
    <CheckOrganModal ref="departModal" @ok="updateQueryParam"></CheckOrganModal>
    <YDModel ref="YDModel" :routerData="$route.path" />
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { columns1, columns2 } from './indexColumns'
import { httpAction, getAction, postAction, deleteAction } from '@/api/manage'
import moment from 'moment'
// import detailModel from './searchResult/index'
import { filterObj } from '@/utils/util'
import LeftTree from './LeftTree.vue'
import { base64toImg } from '@/mixins/base64toImg'
import CheckOrganModal from '@/views/sj/sjxmzygl/yzzx/testcomponent/CheckOrganModal'
import YDModel from '@/views/sj/components/YDModel'
import jumpConfigMixin from '@/views/sj/sjxmzygl/sjxmss/jumpConfigMixin'

export default {
  name: 'zlfx',
  mixins: [base64toImg,jumpConfigMixin],
  components: { LeftTree, CheckOrganModal, YDModel},
  data() {
    return {
      // 表头
      columns1: columns1(this),
      columns2: columns2(this),
      queryParam: {
        accYear: moment().format('YYYY'),
        cutOffTime: moment().format('YYYY-MM-DD'),
        dayNum: 365,
        accName: '',
        accCode: '',
        unitId: '',
      },
      superParam: {
        subjectCode: '',
      },
      isBackButton: false,
      yearPickShow: false,
      dataSource1: [],
      dataSource2: [],
      typeList: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      /* table加载状态 */
      loading: false,
      tableShow: false,
      tableShow2: false,
      subjectChildCode: '',
      rules: {
        cutOffTime: [{ required: true, message: '请选择截止日期' }],
        dayNum: [{ required: true, message: '请输入年度天数单位' }],
        accYear: [{ required: true, message: '请选择单位年度' }],
        accName: [{ required: true, message: '请选择账套' }],
        // accName: [{ required: true, message: '请选择账套' }],
      },
      url: {
        list: '/sjkmfx/sjSubjectsAnalyse/queryAgingInfo',
        list2: '/sjkmfx/sjSubjectsAnalyse/queryAgingDetail',
      },
    }
  },
  computed: {
    param() {
      return this.getQueryParams()
    },
  },
  watch: {
    $route: {
      handler: function (to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.$nextTick(() => {
            this.$refs.leftTree.onSelect(to.query.subjectCode)
            this.searchQuery()
          })
        } else if (Object.keys(to.params).length && to.params.from == 'sjxmss') {
          let { accName, accId } = to.params
          this.queryParam.accName = accName
          this.queryParam.accCode = accId
          // this.queryParam.subjectCode = '1001'

          let {endDate,startDate} = JSON.parse(to.params.returnRecord)
          this.queryParam.cutOffTime = endDate

          this.isBackButton = true
          this.returnRecord = to.params.returnRecord
          this.$nextTick(() => {
            this.searchQuery()
          })
        }
      },
      immediate: true,
    },
  },
  methods: {
    searchReset() {
      this.queryParam = this.$options.data().queryParam
      this.dataSource1 = []
      this.dataSource2 = []
      this.tableShow2 = false
      this.ipagination = this.$options.data().ipagination
    },
    updateQueryParam(data) {
      console.log(data, 'daat')
      let str1 = ''
      let str2 = ''
      let str3 = ''
      data.map((item) => {
        // TODO 账套～～～
        str1 += item.accCode + ','
        str2 += item.accName + ','
        str3 += item.unitId + ','
      })
      if (str1.length > 0) {
        str1 = str1.substr(0, str1.length - 1)
      }
      if (str2.length > 0) {
        str2 = str2.substr(0, str2.length - 1)
      }
      if (str3.length > 0) {
        str3 = str3.substr(0, str3.length - 1)
      }
      this.queryParam.accCode = str1
      this.queryParam.accName = str2
      this.queryParam.unitId = str3
    },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    Rowclick(record, index) {
      let _this = this
      // _this.ipagination.current = 1
      var param = this.getQueryParams()
      let params = {
        ...param,
        subjectCode: record.subjectChildCode,
      }
      return {
        on: {
          click: () => {
            _this.subjectChildCode = record.subjectChildCode
            // console.log(this.subjectChildCode, 'this.subjectChildCode````')
            _this.ipagination.current = 1
            let params = {
              ..._this.getQueryParams(),
              subjectCode: record.subjectChildCode,
            }
            _this.loadMX(params, 1)
            // _this.loadMX(1)
          },
        },
      }
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination, '111')
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      console.log(this.queryParam, '111')
      let param = this.getQueryParams()
      let params = {
        ...param,
        subjectCode: this.subjectChildCode,
      }
      this.getMX(params)
    },
    getTreeData(data) {
      // console.log(data,'data');
      this.superParam.subjectCode = data
      if (data) {
        this.tableShow = true
      }
    },
    handlePanelChange(value) {
      this.queryParam.accYear = moment(value).format('YYYY')
      this.yearPickShow = false
      this.$refs.ruleForm.validateField('accYear', (error) => {
        console.log(error)
      })
    },
    // 弹出日历和关闭日历的回调
    handleOpenChange(status) {
      this.yearPickShow = status
    },
    loadMX(params, arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.getMX(params)
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      this.getZL(params)
      this.loading = true
    },
    getZL(params) {
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource1 = res.result.records || res.result
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getMX(params) {
      getAction(this.url.list2, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource2 = res.result.records || res.result
          this.tableShow2 = true
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      if (this.superParam) {
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters, this.superParam)
      } else {
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      }
      // param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    searchQuery() {
      this.dataSource1 = []
      this.dataSource2 = []
      this.tableShow2 = false
      this.loadData(1)
      if (typeof this.getTop === 'function') {
        this.getTop()
      }
    },
    // searchReset() {
    //   this.queryParam = {}
    //   this.loadData(1)
    // },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
</style>
<style lang="less" scoped>
.pointer_table {
  /deep/ .ant-table-row {
    cursor: pointer;
  }
}
</style>